<template>
  <view class="container">
    <!-- 备货出库 -->
    <view class="wrapper">
      <!-- <view class="title">备货出库</view>	 -->
      <scroll-view scroll-y class="scroll-view">
        <view class="merchant-title">
          <!-- {{ merchant.merName || '商家' + (mIdx + 1) }} -->
          订单商品
        </view>
        <view v-if="isAdd">
        <view
          class="merchant-card"
          v-for="(merchant, mIdx) in orderInfo.merchantOrderList"
          :key="mIdx"
        >
          <view class="item-list">
            <view
              class="item"
              v-for="item in merchant.orderInfoList"
              :key="item.id"
            >
              <image class="image" :src="item.image" mode="aspectFill" />
              <view class="info">
                <view class="name">{{ item.productName }}</view>
                <view class="sku">{{ item.sku }}</view>
              </view>
              <view class="action">
                <view class="price-info">
                  <view class="price">￥{{ item.price }}</view>
                  <view class="num">x{{ item.payNum }}</view>
                </view>
                <view class="btn-spec" @click="addSpec(item)" v-if="isAdd"
                  >添加规格</view
                >
              </view>
            </view>
          </view>
        </view>

        </view>
        <view v-else class="merchant-card">
          <view class="item-card" v-for="(item,index) in defOrderInfo" :key="index">
           <view class="item-list">
            <view
              class="item"
            >
              <image class="image" :src="item.image" mode="aspectFill" />
              <view class="info">
                <view class="name">{{ item.productName }}</view>
                <view class="sku">{{ item.sku }}</view>
              </view>
              <view class="action">
                <view class="price-info">
                  <view class="price">￥{{ item.price }}</view>
                  <view class="num">x{{ item.number }}</view>
                </view>
                <view class="btn-spec" @click="addSpec(item)" v-if="isAdd"
                  >添加规格</view
                >
              </view>
            </view>
          </view>
          </view>
        </view>
        <!-- 补充商品 -->
        <view class="item-card" v-if="selectAttrList.length > 0">
          <view class="item-title">补充商品</view>
          <view class="item-list">
            <view
              class="item"
              v-for="(item, index) in selectAttrList"
              :key="item.id"
            >
              <image class="image" :src="item.image" mode="aspectFill" />
              <view class="info">
                <view class="name">{{ item.productName }}</view>
                <view class="sku">{{ item.sku }}</view>
              </view>
              <view class="action">
                <view class="price-info">
                  <view class="price">￥{{ item.price }}</view>
                  <view class="num">x{{ item.number }}</view>
                </view>
                <view class="btn-remove" @click="removeItem(index)" v-if="isAdd"
                  >移除商品</view
                >
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="footer" v-if="isAdd">
      <view class="btn-cancel" @click="cancel">取消</view>
      <view class="btn-confirm" @click="confirmShipment">确认出库</view>
    </view>

    <uni-popup
      @maskClick="maskClick"
      ref="popup"
      type="center"
      background-color="#fff"
      border-radius="10px 10px 0 0"
    >
      <product-cttr
        ref="productCttr"
        :product-select="productSelect"
        :product-attr="productAttr"
        :cart-attr="cartAttr"
        :sku-list="skuList"
        @confirmShipment="confirmShipmentAttr"
        @closeAttr="closeAttr"
        v-if="isShowAttr"
      />
    </uni-popup>
  </view>
</template>

<script>
import {
  getOrderDetail,
  getProductSpecs,
  saleRoomIsSureOut,
  getStockUpDetails,
} from "@/api/index.js";
import ProductCttr from "@/components/product-cttr/product-cttr.vue";
export default {
  components: {
    ProductCttr,
  },
  data() {
    return {
      orderNo: "",
      orderInfo: { merchantOrderList: [] },
      supplementaryItems: [],
      productInfo: {},
      productSelect: {},
      productAttr: [],
      cartAttr: false,
      skuList: [],
      selectAttrList: [],
      isAdd: false,
      isShowAttr: false,
      defOrderInfo:[]
    };
  },
  onLoad(options) {
    this.orderNo = options.orderNo;
    if (options.isAdd == 1) {
      this.isAdd = true;
      this.getOrderInfo();

    } else {
      this.getStockUpDetailsList();
    }
  },
  methods: {
    closeAttr() {
      this.$refs.popup.close();
      this.isShowAttr = false;
    },
    getStockUpDetailsList() {
      getStockUpDetails(this.orderNo)
        .then((res) => {
          console.log("备货详情", res);
          this.selectAttrList = res.data.addList;
          // this.orderInfo.merchantOrderList = res.data.originalList;
          this.defOrderInfo = res.data.originalList;
          console.log("备货详情", this.orderInfo);
        })
        .catch((err) => {
          console.log("备货详情失败", err);
        });
    },
    confirmShipmentAttr() {
      console.log("确认出库");
      const cttr = this.$refs.productCttr;
      if (cttr) {
        // 判断是否所有属性都已选中
        const allSelected = cttr.productAttr.every((attr) => attr.index);
        if (allSelected) {
          // 保存选中的规格信息
          const selectedSku = cttr.skuList.find((sku) => {
            const attrValue = JSON.parse(sku.attrValue);
            return cttr.productAttr.every(
              (attr) => attr.index && attrValue[attr.attrName] === attr.index
            );
          });
          const selectedInfo = {
            sku: selectedSku,
            number: cttr.productSelect.cart_num,
            attr: cttr.productAttr.map((attr) => ({
              name: attr.attrName,
              value: attr.index,
            })),
          };
          // 关闭弹窗
          this.cartAttr = false;
          this.$refs.popup.close();
          // 检查 selectAttrList 是否已有相同 sku
          const existIdx = this.selectAttrList.findIndex(
            (item) => item.sku === selectedSku.sku
          );
          if (existIdx > -1) {
            // 累加数量
            this.selectAttrList[existIdx].number += selectedInfo.number;
            this.supplementaryItems[existIdx].number += selectedInfo.number;
          } else {
            this.supplementaryItems.push(selectedInfo);
            this.selectAttrList.push({
              ...selectedInfo.sku,
              number: selectedInfo.number,
            });
          }
          console.log("补充商品", this.selectAttrList);
        } else {
          uni.showToast({ title: "请先选择完整规格", icon: "none" });
        }
      }
    },
    maskClick() {
      this.$refs.popup.close();
      this.isShowAttr = false;
      // 获取 product-cttr 组件实例
      return;
    },
    getOrderInfo() {
      let that = this;
      uni.showLoading({ title: "正在加载中" });
      getOrderDetail(that.orderNo)
        .then((res) => {
          uni.hideLoading();
          let data = res.data;
          that.$set(that, "orderInfo", data);
          if (!this.isAdd && data.inOrOutWarehouseSkuDetailsList.length > 0) {
            // that.getStockUpDetailsList();
            // that.$set(
            //   that,
            //   "selectAttrList",
            //   data.inOrOutWarehouseSkuDetailsList
            // );
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    addSpec(item) {
      getProductSpecs(item.productId).then((res) => {
        this.isShowAttr = true;

        // 转换为 product-cttr 组件需要的格式
        const skuList = res.data || [];
        // 1. 解析所有属性
        const attrMap = {};
        skuList.forEach((sku) => {
          const attrValue = JSON.parse(sku.attrValue);
          Object.entries(attrValue).forEach(([key, value]) => {
            if (!attrMap[key]) attrMap[key] = new Set();
            attrMap[key].add(value);
          });
        });
        // 2. 生成 productAttr（只包含 skuList 中实际存在的属性值）
        const productAttr = Object.entries(attrMap).map(
          ([attrName, valueSet]) => ({
            attrName,
            index: "", // 默认未选
            optionList: Array.from(valueSet)
              .filter((optionName) => {
                // 只保留 skuList 中有的属性值
                return skuList.some((sku) => {
                  const attrValue = JSON.parse(sku.attrValue);
                  return attrValue[attrName] === optionName;
                });
              })
              .map((optionName) => ({
                optionName,
                image:
                  (
                    skuList.find((sku) => {
                      const attrValue = JSON.parse(sku.attrValue);
                      return attrValue[attrName] === optionName && sku.image;
                    }) || {}
                  ).image || "",
              })),
          })
        );
        // 3. 默认选中第一个 sku 作为 productSelect
        const firstSku = skuList[0] || {};
        console.log("firstSku", firstSku);
        const productSelect = {
          image: firstSku.image,
          name: item.productName || firstSku.productName || "",
          stock: firstSku.transferOutStoreThenStock,
          groupPrice: firstSku.groupPrice,
          groupStock: firstSku.groupStock,
          cart_num: 1,
          max_num: firstSku.stock,
          price: firstSku.price,
          sku: firstSku.sku,
          id: firstSku.id,
        };
        this.productAttr = productAttr;
        this.productSelect = productSelect;
        this.skuList = skuList;
        this.cartAttr = true;
        this.$refs.popup.open();
      });
    },
    removeItem(index) {
      this.supplementaryItems.splice(index, 1);
      this.selectAttrList.splice(index, 1);
    },
    cancel() {
      uni.navigateBack();
    },
    confirmShipment() {
		console.log(this.orderInfo)
      // 主商品
      const mainItems = (this.orderInfo.merchantOrderList || [])
        .flatMap((m) =>
          (m.orderInfoList || [])
        )
        .map((item) => ({
          barCode: item.barCode || "",
          image: item.image || "",
          isAddSpecs: 0,
          itemNumber: item.itemNumber || "",
          number: item.payNum || 0,
          price: item.price || 0,
          productAttrValueId: item.attrValueId || 0,
          productId: item.productId || 0,
          productName: item.productName || "",
          sku: item.sku || "",
          transferInStoreThenStock: 0,
          transferOutStoreThenStock: 0,
          unitName: item.unitName || "",
        }));
		
      // 补充商品
      const supplementItems = this.supplementaryItems.map((item) => {
        const sku = item.sku || {};
        return {
          barCode: sku.barCode || "",
          image: sku.image || "",
          isAddSpecs: 1,
          itemNumber: sku.itemNumber || "",
          number: item.number || 0,
          price: sku.price || 0,
          productAttrValueId: sku.id || sku.productAttrValueId || 0,
          productId: sku.productId || 0,
          productName: sku.productName || "",
          sku: sku.sku || "",
          transferInStoreThenStock: 0,
          transferOutStoreThenStock: 0,
          unitName: sku.unitName || "",
        };
      });
	  
	   console.log("jjj", mainItems, supplementItems)
	  
      // 合并
      const purchaseInWarehouseFormSkuListRequestList = [
        ...mainItems,
        ...supplementItems,
      ];
	 
      console.log("全部商品参数", purchaseInWarehouseFormSkuListRequestList);
      saleRoomIsSureOut({
        purchaseInWarehouseFormSkuListRequestList,
        orderNo: this.orderNo,
      }).then((res) => {
		  if(res.code===200) {
			  uni.showToast({ title: "出库成功", icon: "success" });
			  console.log("出库成功", res);
			  setTimeout(() => {
			    // uni.navigateBack();
          uni.redirectTo({
            url: '/pages/orderManage/orderManage'
          });
			  }, 500);
		  }else{
			   uni.showToast({ title: res.message, icon: "none" });
		  }
        })
        .catch((err) => {
			uni.showToast({ title: err, icon: "none" });
          console.log("出库失败", err);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  background: #f2f2f2;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;

  .wrapper {
    width: 95vw;
    // max-width: 900px;
    // min-width: 320px;
    background: #fff;
    border-radius: 10px;
    margin: 2vw 0;
    display: flex;
    flex-direction: column;
    .title {
      text-align: center;
      font-size: 2rem;
      font-weight: bold;
      padding: 1.5vw 0;
      border-bottom: 1px solid #eee;
    }
  }
  .scroll-view {
    flex: 1;
    padding: 0 2vw;
    overflow-y: auto;
  }
  .merchant-title {
    font-size: 1.2rem;
    color: #007bff;
    font-weight: bold;
    margin: 2vw 0 1vw 0;
  }
  .item-list .item {
    display: flex;
    align-items: center;
    padding: 1vw 0;
    border-bottom: 1px solid #eee;
    .image {
      width: 8vw;
      min-width: 60px;
      max-width: 100px;
      height: 8vw;
      min-height: 60px;
      max-height: 100px;
      border-radius: 5px;
      background: #eee;
    }
    .info {
      flex: 1;
      margin: 0 1vw;
      .name {
        font-size: 1rem;
        color: #333;
        font-weight: 500;
      }
      .sku {
        font-size: 0.9rem;
        color: #999;
        margin-top: 0.5vw;
      }
    }
    .action {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      .price-info {
        .price {
          font-size: 1rem;
          color: #333;
        }
        .num {
          font-size: 0.9rem;
          color: #999;
        }
      }
      .btn-spec,
      .btn-remove {
        margin-top: 1vw;
        font-size: 1rem;
        cursor: pointer;
      }
      .btn-spec {
        color: #007bff;
      }
      .btn-remove {
        color: #ff4d4f;
      }
    }
  }
  .item-card {
    margin-top: 2vw;
    .item-title {
      font-size: 1.1rem;
      font-weight: bold;
      color: #999;
      margin-bottom: 1vw;
    }
  }
  .footer {
    width: 95vw;
    max-width: 900px;
    display: flex;
    justify-content: flex-end;
    padding: 2vw;
    .btn-cancel,
    .btn-confirm {
      padding: 1vw 3vw;
      border-radius: 20px;
      font-size: 1rem;
      margin-left: 1vw;
    }
    .btn-cancel {
      background: #fff;
      border: 1px solid #ccc;
      color: #333;
    }
    .btn-confirm {
      background: #007bff;
      color: #fff;
    }
  }
}
@media (max-width: 600px) {
  .container .wrapper,
  .container .footer {
    width: 100vw !important;
    min-width: 0 !important;
    max-width: 100vw !important;
    padding: 0 2vw;
  }
  .container .item-list .item .image {
    width: 20vw;
    height: 20vw;
    min-width: 40px;
    min-height: 40px;
    max-width: 80px;
    max-height: 80px;
  }
}
</style>
